package com;


import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@WebServlet("/blogListPage")
public class BlogServletPage extends HttpServlet {
    DbUtil dbUtil = new DbUtil();

    public void init() throws ServletException
    {
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            /*1.查询总记录数。

            2.设置记录数，自动计算总页数。

            3.由当前页号计算查询起始点。

            4.把当前页数据封装到List<T>里面。

            5.转发跳转到展示页。*/
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            String current = req.getParameter("current") != null ? req.getParameter("current") : 1+"";
            String pageSize = req.getParameter("pageSize") != null ? req.getParameter("pageSize") : 10+"";
            Page<Blog> page = new Page<Blog>(Integer.parseInt(current),Integer.parseInt(pageSize));
            Integer blogCount = dbUtil.getBlogCount();
            page.setCount(blogCount);
            List<Blog> blogListPage = dbUtil.getBlogList(page);
            page.setObjList(blogListPage);
            //响应的是json
            resp.setContentType("application/json;charset=utf-8");
            //获得对象的json格式数据
            String jsonRes =  JSON.toJSONString(page);;//gson,jaskon
            resp.getOutputStream().write(jsonRes.getBytes(StandardCharsets.UTF_8));
            resp.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void destroy()
    {
        // 什么也不做
    }
}
